package com.hao.thread;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;

/**
 * @author haohj
 * @date 2020-04-29 08:47
 */
public class FutureTest {
    public void funA() {
        ExecutorService executorService = Executors.newCachedThreadPool();
        List<Future<String>> futureList = new ArrayList<>();

        //创建10个任务并执行
        for (int i = 0; i < 10; i++) {
            //使用executorService执行Callable类型的任务，并且将结果保存在Future中
            Future<String> future = executorService.submit(new CallAbleTask(i));
            //将任务执行结果存到list中
            futureList.add(future);
        }

        futureList.forEach(future-> {
            try {
                System.out.println(future.get()+"执行结果");
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
    }

    public class CallAbleTask implements Callable<String> {
        private int id;

        public CallAbleTask(int id) {
            this.id = id;
        }

        @Override
        public String call() throws Exception {
            System.out.println("call方法被自动调用，开始干活  " + Thread.currentThread().getName());
            Thread.sleep(1000);
            return "返回" + id + "---" + Thread.currentThread().getName();
        }
    }

    public static void main(String[] args) {
        FutureTest test = new FutureTest();
        test.funA();
    }
}
